from django.shortcuts import render
from rest_framework import status
from rest_framework.generics import GenericAPIView,CreateAPIView,RetrieveAPIView, UpdateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.mixins import CreateModelMixin, RetrieveModelMixin,UpdateModelMixin
from rest_framework.permissions import IsAuthenticated
from rest_framework.viewsets import ViewSet, GenericViewSet

from users import constants
from users.models import User
from users.serializers import UserSerializer, UserDetailSerializer, EmailSerializer, AddressSerializer


# Create your views here.

#  POST /authorizations/

# class UserAuthorizeView(APIView):
#     def post(self, request):
#         """
#         用户登陆
#         1. 获取参数username和password并惊醒校验（参数完整性,用户名不能全部为数字，用户名和密码是否正确）
#         2. 生成jwt token 保存登陆用户身份信息
#         3.返回响应，登陆成功
#         :param request:
#         :return:
#         """
#         pass



class AddressViewSet(CreateModelMixin, GenericViewSet):
    permission_classes = [IsAuthenticated]
    serializer_class = AddressSerializer

    # POST /address/
    def create(self, request):
        """
        登陆用户地址新增
        0.判断用户的地址数量是否超过数量上限
        1.获取参数并进行校验（参数完整性，手机号格式，邮箱格式）
        2.创建并保存新增地址数据
        3.将新增地址序列化并返回
        :param request:
        :return:
        """
        # 0.判断用户的地址数量是否超过数量上限
        count = request.user.addressess.filter(is_deleted=False).count()

        if count >= constants.USER_ADDRESS_COUNTS_LIMIT:
            return Response({'message': '地址数量超过上限'}, status=status.HTTP_400_BAD_REQUEST)

        # #1.获取参数并进行校验（参数完整性，手机号格式，邮箱格式）
        # serializer = self.get_serializer(data=request.data)
        # serializer.is_valid(raise_exception=True)
        #
        # # 2.创建并保存新增地址数据(create)
        # serializer.save()
        #
        # # 3.将新增地址序列化并返回
        # return Response(serializer.data, status=status.HTTP_201_CREATED)

        # 调用CreateModelMixin中的create方法
        return super().create(request)


# PUT /emails/verification/?token=<加密用户的信息>
class EmailVerifyView(APIView):
    def put(self, request):
        """
        用户邮箱验证
        1.获取token并进行校验（token必传，token是否有效）
        2.设置对应用户的邮箱验证标记email_active为True
        3.返回应答，验证成功
        :param request:
        :return:
        """
        #1.获取token并进行校验（token必传，token是否有效）
        token = request.query_params.get('token') # None
        if token is None:
            return Response({'message': '缺少token参数'}, status=status.HTTP_400_BAD_REQUEST)
        # 对token进行解密
        user = User.check_email_verify_token(token)

        if user is None:
            return Response({'message': '无效的token'}, status=status.HTTP_400_BAD_REQUEST)

        # 2.设置对应用户的邮箱验证标记email_active为True
        user.email_active = True
        user.save()

        # 3.返回应答，验证成功
        return Response({'message': 'OK'})

# PUT /email/
class EmailView(UpdateAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = EmailSerializer

    def get_object(self):
        """重写返回登陆用户对象"""
        return self.request.user

    # def put(self, request):
    #     """
    #     登陆用户的邮箱设置
    #     1.获取参数并进行校验（email必传，email格式)
    #     2.设置登陆用户的邮箱并给邮箱发送验证邮件
    #     3.返回赢得，邮箱设置成功
    #     """
    #     # 获取登陆用户
    #     user = self.get_object()
    #
    #     #1.获取参数并进行校验（email必传，email格式)
    #     serializer = self.get_serializer(user, data=request.data)
    #     serializer.is_valid(raise_exception=True)
    #
    #     # 2.设置登陆用户的邮箱并给邮箱发送验证邮件(update)
    #     serializer.save()
    #
    #     # 3.返回赢得，邮箱设置成功
    #     return Response(serializer.data)


# GET /user/  默认认证权限
class UserDetailView(RetrieveAPIView):
    # 只有认证过的才能进行访问
    permission_classes = [IsAuthenticated]
    serializer_class = UserDetailSerializer

    def get_object(self):
        """返回登陆用户对象"""
        # self.request:request对象
        return self.request.user



    # def get(self, request):
    #     """
    #     request.user
    #     获取登陆用户基本信息
    #     1.获取登陆用户
    #     2.将登陆用户对象序列化并烦的
    #     """
    #     #1.获取登陆用户
    #     user = self.get_object()
    #
    #     # 2.将登陆用户对象序列化并烦的
    #     serializer = self.get_serializer(user)
    #     return Response(serializer.data)


# POST /users/
class UserView(CreateAPIView):
    # 指定视图所使用的序列化器类
    serializer_class = UserSerializer

    #在CreateAPIView中已经存在了
    # def post(self, request):
    #     """
    #     注册用户的信息保存
    #     1.获取参数并进行校验（参数完整性，两次密码是否一致，手机号格式，
    #     手机号是否存在，短信验证码是否正确，是否同意协议）
    #     2.创建新用户并保存到数据库
    #     3.注册成功，将新用户对象序列化并返回
    #     :param request:
    #     :return:
    #     """
    #     #1.获取参数并进行校验（参数完整性，两次密码是否一致，手机号格式，
    #     # 手机号是否存在，短信验证码是否正确，是否同意协议）
    #     serializer = self.get_serializer(data=request.data)
    #     serializer.is_valid(raise_exception=True)
    #
    #     # 2.创建新用户并保存到数据库(create)
    #     serializer.save()
    #
    #
    #     # 3.注册成功，将新用户对象序列化并返回
    #     return Response(serializer.data, status=status.HTTP_201_CREATED)


# GET usernames/(?P<username>\w{5,20})/count/
class UsernameCountView(APIView):
    def get(self, request, username):
        """
        获取用户名数量
        1.根据用户名查询数据库，获取查询结果数量
        2.返回用户名数量
        """
        #1.根据用户名查询数据库，获取查询结果数量
        count = User.objects.filter(username=username).count()

        # 2.返回用户名数量
        res_data = {
            'username': username,
            'count': count
        }
        return Response(res_data)


#  GET mobiles/(?P<mobile>1[3-9]\d{9})/count/
class MobileCountView(APIView):
    def get(self, request, mobile):
        """
        获取手机号数量
        1.根据手机号查询数据库，获取查询结果数量
        2.返回手机号数量
        """
        #1.根据手机号查询数据库，获取查询结果数量
        count = User.objects.filter(username=mobile).count()

        # 2.返回手机号数量
        res_data = {
            'mobile': mobile,
            'count': count
        }
        return Response(res_data)
